package com.smzd.framework.sso;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;

import com.smzd.framework.security.domain.Authority;
import com.smzd.framework.system.domain.User;
import com.smzd.framework.utils.MeetingSessionHolder;
import com.smzd.framework.utils.URIStacks;

public class PreparedAuthenticationProcessingFilter extends
        AbstractAuthenticationProcessingFilter {
    private final static List<GrantedAuthority> authorities = Arrays
            .asList((GrantedAuthority) new Authority("ROLE_USER"));
    
    protected PreparedAuthenticationProcessingFilter(
            String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    public PreparedAuthenticationProcessingFilter() {
        this("/sso/preparedauth");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException,
            IOException, ServletException {
        HttpSession session = request.getSession();
        User preparedUser = (User) session.getAttribute(MeetingSessionHolder.KEY_PREPARED_USER);
        if (preparedUser == null) {
            throw new AuthenticationCredentialsNotFoundException("用户没有准备好！");
        }
        //清空Session中存储的准备好的用户
        session.removeAttribute(MeetingSessionHolder.KEY_PREPARED_USER);
        URIStacks stacks = (URIStacks) session.getAttribute(URIStacks.URISTACKS_SESSION_KEY);
        if (stacks == null) {
            throw new SessionAuthenticationException("没有URIStacks！");
        }
        if (stacks.size()<=0) {
            throw new SessionAuthenticationException("URIStacks是空的！");
        }
        session.setAttribute(URIStacks.SPRING_SECURITY_SAVED_REQUEST, stacks.pop());
        if(preparedUser.getAuthorities()==null){
            preparedUser.setAuthorities(authorities);
        }
        return new UsernamePasswordAuthenticationToken(preparedUser,
                preparedUser.getPassword(), preparedUser.getAuthorities());
    }

}
